package org.opens.service.impl;

import cn.hutool.core.lang.Assert;
import org.opens.dao.EduCourseDao;
import org.opens.entity.EduCourse;
import org.opens.pattern.DatePattern;
import org.opens.service.EduCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

@Service
public class EduCourseServiceImpl implements EduCourseService {

    @Autowired
    private EduCourseDao eduCourseDao;

    @Override
    public Optional<EduCourse> findById(Integer id) {
        Assert.notNull(id);

        return Optional.ofNullable(eduCourseDao.findById(id));
    }

    @Override
    public List<EduCourse> findByScheduledStartDatetime(String startDate) {
        Assert.notEmpty(startDate);

        LocalDateTime scheduledStartDatetime = null;

        if (startDate.length() > 10) {
            // 验证时间字符串格式
            Assert.isTrue(startDate.matches(DatePattern.ISO_DATETIME_REGEX), "时间格式错误: " + startDate);

            scheduledStartDatetime = LocalDateTime.parse(startDate, DateTimeFormatter.ofPattern(cn.hutool.core.date.DatePattern.NORM_DATETIME_PATTERN));
        } else {
            // 验证时间字符串格式
            Assert.isTrue(startDate.matches(DatePattern.ISO_DATE_REGEX), "时间格式错误: " + startDate);

            LocalDate scheduledStartDate = null;
            LocalTime scheduledStartTime = null;
            scheduledStartDate = LocalDate.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE);
            scheduledStartTime = LocalTime.of(0, 0, 0);
            scheduledStartDatetime = LocalDateTime.of(scheduledStartDate, scheduledStartTime);
        }

        return eduCourseDao.findByScheduledStartDatetime(scheduledStartDatetime);
    }

    @Override
    public int save(EduCourse eduCourse) {
        Assert.notNull(eduCourse);

        return eduCourseDao.insert(eduCourse);
    }
}
